import { defineStore } from 'pinia';

interface TabItem {
	key: string;
	label: string;
	path: string;
	closable: boolean;
}

interface TabState {
	tabs: TabItem[];
	activeTab: string;
}

export const useTabStore = defineStore('tab', {
	state: (): TabState => ({
		tabs: [
			{
				key: 'index',
				label: '首页',
				path: '/',
				closable: false,
			},
		],
		activeTab: 'index',
	}),

	actions: {
		// 添加标签
		addTab(tab: Omit<TabItem, 'closable'>) {
			const existTab = this.tabs.find((item) => item.path === tab.path);
			if (existTab) {
				this.activeTab = existTab.key;
				return;
			}

			this.tabs.push({
				...tab,
				closable: true,
			});
			this.activeTab = tab.key;
		},

		// 关闭标签
		closeTab(key: string) {
			const index = this.tabs.findIndex((tab) => tab.key === key);
			if (index === -1) return;

			this.tabs.splice(index, 1);

			// 如果关闭的是当前激活的标签，则激活前一个标签
			if (key === this.activeTab) {
				this.activeTab = this.tabs[Math.max(0, index - 1)].key;
			}
		},

		// 关闭所有标签
		closeAllTabs() {
			this.tabs = [this.tabs[0]]; // 保留首页
			this.activeTab = this.tabs[0].key;
		},

		// 关闭左侧标签
		closeLeftTabs(key: string) {
			const index = this.tabs.findIndex((tab) => tab.key === key);
			if (index === -1) return;

			// 保留首页和当前标签
			const firstTab = this.tabs[0];
			const currentTab = this.tabs[index];
			this.tabs = [firstTab];
			
			if (index > 0) {
				this.tabs.push(currentTab);
				this.tabs.push(...this.tabs.slice(index + 1));
			}

			this.activeTab = key;
		},

		// 关闭右侧标签
		closeRightTabs(key: string) {
			const index = this.tabs.findIndex((tab) => tab.key === key);
			if (index === -1) return;

			this.tabs = this.tabs.slice(0, index + 1);
			this.activeTab = key;
		},

		// 关闭其他标签
		closeOtherTabs(key: string) {
			const tab = this.tabs.find((tab) => tab.key === key);
			if (!tab) return;

			// 保留首页和当前标签
			const firstTab = this.tabs[0];
			this.tabs = [firstTab];
			
			if (key !== firstTab.key) {
				this.tabs.push(tab);
			}

			this.activeTab = key;
		},

		// 设置当前激活的标签
		setActiveTab(key: string) {
			this.activeTab = key;
		},

		// 重置标签页
		resetTabs() {
			this.tabs = [
				{
					key: 'index',
					label: '首页',
					path: '/',
					closable: false,
				},
			];
			this.activeTab = 'index';
		},
	},
});

export const useTabStoreHook = () => useTabStore(); 